#!/bin/bash

# Maven 版本和下载 URL
MAVEN_VERSION="3.9.11"
MAVEN_URL="https://dlcdn.apache.org/maven/maven-3/3.9.11/binaries/apache-maven-3.9.11-bin.tar.gz"
MAVEN_HOME="/opt/maven"

echo "开始安装 Maven ${MAVEN_VERSION}..."

# 检查是否以 root 权限运行
if [ "$EUID" -ne 0 ]; then 
    echo "请使用 sudo 运行此脚本"
    exit 1
fi

# 创建临时目录
TMP_DIR=$(mktemp -d)
cd "$TMP_DIR"

# 下载 Maven
echo "下载 Maven ${MAVEN_VERSION}..."
curl -L "$MAVEN_URL" -o "maven.tar.gz" \
  --progress-bar \
  --retry 3 \
  --retry-delay 5 \
  --retry-max-time 60

# 检查下载是否成功
if [ $? -ne 0 ]; then
    echo "Maven 下载失败"
    rm -rf "$TMP_DIR"
    exit 1
fi

# 创建安装目录
echo "创建安装目录..."
rm -rf "$MAVEN_HOME"
mkdir -p "$MAVEN_HOME"

# 解压 Maven
echo "解压 Maven..."
tar -xzf "maven.tar.gz" -C "$MAVEN_HOME" --strip-components=1

# 配置 Maven 镜像
echo "配置 Maven 阿里云镜像..."
MAVEN_SETTINGS="${MAVEN_HOME}/conf/settings.xml"
# 备份原始设置文件
cp "${MAVEN_SETTINGS}" "${MAVEN_SETTINGS}.backup"

# 创建新的 settings.xml 文件
cat > "${MAVEN_SETTINGS}" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <mirrors>
    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
</settings>
EOF

# 设置环境变量
MAVEN_ENV_FILE="/etc/profile.d/maven.sh"
echo "配置环境变量..."
cat > "$MAVEN_ENV_FILE" << EOF
export MAVEN_HOME=$MAVEN_HOME
export PATH=\$MAVEN_HOME/bin:\$PATH
EOF

# 设置权限
chmod +x "$MAVEN_ENV_FILE"

# 使环境变量立即生效
source "$MAVEN_ENV_FILE"

# 清理临时文件
rm -rf "$TMP_DIR"

# 验证安装
echo "验证 Maven 安装..."
mvn -version

echo "Maven ${MAVEN_VERSION} 安装完成！"
echo "环境变量已配置，请选择以下方式之一使其生效："
echo "1. 执行: source /etc/profile"
echo "2. 执行: exec bash"
echo "3. 重新打开终端" 